﻿using AutoMapper;
using MediatR;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.RBAC;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.Permission;

namespace RBAC.Read.Api.Application.Handler.Permission
{
    public class GetPermissionHandler : IRequestHandler<GetPermissionCommand, APIResult<List<GetPermissionListDto>>>
    {
        private readonly IBaseRepository<PermissionModel> permissionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetPermissionHandler> logger;

        public GetPermissionHandler(IBaseRepository<PermissionModel> permissionRepository, IMapper mapper, ILogger<GetPermissionHandler> logger)
        {
            this.permissionRepository = permissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<GetPermissionListDto>>> Handle(GetPermissionCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<GetPermissionListDto>> res = new APIResult<List<GetPermissionListDto>>();
            
            try
            {
                res.Code = APIEnums.Success;
                res.Data = GetTreee(0);
                res.Msg = "获取成功";
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Error;
                res.Msg = "获取权限列表失败";
                logger?.LogError(ex, "获取权限列表失败: {Message}", ex.Message);
            }
            
            return Task.FromResult(res);
        }

        private List<GetPermissionListDto> GetTreee(long parentId)
        {
            try
            {
                // 使用Dapper查询权限数据
                var sql = "SELECT * FROM Permission WHERE ParentId = @ParentId AND IsDeleted = false";
                var parameters = new { ParentId = parentId };
                var permission = permissionRepository.Query<PermissionModel>(sql, parameters);
                
                var dto = mapper.Map<List<GetPermissionListDto>>(permission);
                foreach (var item in dto)
                {
                    item.Children = GetTreee(item.Id);
                }
                return dto;
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "获取权限树失败，ParentId: {ParentId}", parentId);
                return new List<GetPermissionListDto>();
            }
        }
    }
}
